package edu.upb.acs.jobsmaps.activity.fileuploader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import edu.upb.acs.jobsmaps.R;
import edu.upb.acs.jobsmaps.database.json.CompanyJsonParser;
import edu.upb.acs.jobsmaps.database.task.AddCompanyTask;
import edu.upb.acs.jobsmaps.database.task.AddJobTask;
import edu.upb.acs.jobsmaps.entity.Company;
import edu.upb.acs.jobsmaps.entity.Job;

import java.util.List;

public class FileExplorerActivity extends Activity {

    private static final int REQUEST_PATH = 1;
	private static final String TAG = FileExplorerActivity.class.getName();

	String curFileName;

    EditText edittext;

    final Context context = this;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fileexplorer);

        edittext = (EditText) findViewById(R.id.editText);

		Button uploadCompanies = (Button) findViewById(R.id.uploadCompaniesFromFileButton);

		uploadCompanies.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                if (edittext.getText() == null || edittext.getText().length() == 0) {
                    alertDialogBuilder.setMessage("No import selected");
                    alertDialogBuilder.setCancelable(false).setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // when the ok button is pushed, return to main
                                    // view
                                    setResult(RESULT_CANCELED);
                                }
                            });

                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                } else {

                    // here i call new screen;
                    Log.d(TAG, "SELECTED FILE = " + edittext.getText());

                    StringBuilder importInfo = new StringBuilder("Information was imported with success:\n\n");
                    List<Company> companies = CompanyJsonParser.parse("/sdcard/" + edittext.getText());

                    for (Company company : companies) {
                        importInfo.append( company.getName() + "\n");
                        importInfo.append("\tjobs: \n");

						AddCompanyTask addCompanyTask = new AddCompanyTask();
						Integer persistedCompanyId = null;
						try {
							persistedCompanyId = addCompanyTask.execute(company).get();
							Log.d(TAG, "New company id = " + persistedCompanyId);
						} catch (Exception e) {
							Log.e(TAG, "Can not persist company", e);
						}

                        if (company.getJobs().size() == 0) {
                            importInfo.append("-\n");
                        } else {
                            for (Job job : company.getJobs()) {
                                importInfo.append("\t\tname : " + job.getName() + "\n");
								if (null != persistedCompanyId){
									job.setCompanyId(persistedCompanyId.toString());
								}

								AddJobTask addJobTask = new AddJobTask();
								try {
									Integer persistedJobId = addJobTask.execute(job).get();
									Log.d(TAG, "New job id = " + persistedJobId);
								} catch (Exception e) {
									Log.e(TAG, "Can not persist job", e);
								}
                            }
                            importInfo.append("\n");
                        }
                    }


                    alertDialogBuilder.setMessage(importInfo.toString());
                    alertDialogBuilder.setCancelable(false).setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    setResult(RESULT_OK);
                                    finish();
                                }
                            });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    // show it
                    alertDialog.show();
                }

            }
        });

    }

    public void getfile(View view) {
        Intent intent1 = new Intent(this, FileChooserActivity.class);
        startActivityForResult(intent1, REQUEST_PATH);
    }

    // Listen for results.
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // See which child activity is calling us back.
        if (requestCode == REQUEST_PATH) {
            if (resultCode == RESULT_OK) {
                curFileName = data.getStringExtra("GetFileName");
                edittext.setText(curFileName);
            }
        }
    }
}
